﻿using Autofac;
using IoTSocket.Sockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XgRobot;

namespace WCS.API.LongTaskService
{
    public class CommunicationService : BackgroundService
    {

        #region Field
        private TcpService tcpServer;
        private readonly ILogger<CommunicationService> logger;

        private readonly ILifetimeScope lifetimeScope;

        public CommunicationService(
            ILogger<CommunicationService> logger,
            ILifetimeScope lifetimeScope)
        {
            this.logger = logger;
            this.lifetimeScope = lifetimeScope;
            tcpServer = new TcpService();
        }
        #endregion


        #region Method

        /// <summary>
        /// 启动时运行
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            #region 后台Tcp任务

            try
            {
                tcpServer.Received += TcpServer_Received;
                tcpServer.Connected += TcpServer_Connected;
                tcpServer.Disconnected += TcpServer_Disconnected;

                tcpServer.Setup(new IoTSocket.Core.IoTSocketConfig().
                    SetDataHandlingAdapter(() => new SeerPackDataHandlingAdapter()).
                        SetListenIPHosts(new IPHost[] { new IPHost(3000) }))
                   .Start();
            }
            catch (Exception ex)
            {
                logger.LogInformation($"Tcp Server start failed! The error info is:{ex.Message}");
            }

            #endregion

            return Task.Delay(500);
        }

        private void TcpServer_Disconnected(SocketClient client, DisconnectEventArgs e)
        {
            logger.LogInformation($"{client.IP} Disconnected!");
        }

        private void TcpServer_Connected(SocketClient client, IoTSocket.Core.IoTSocketEventArgs e)
        {
            logger.LogInformation($"{client.IP} Connected!");
        }

        private void TcpServer_Received(SocketClient client, IoTSocket.Core.ByteBlock byteBlock, IRequestInfo requestInfo)
        {
            try
            {
                if (requestInfo is SeerPack pack)
                {
                    logger.LogInformation("Receive the rms {0} info is:{1}", client.IP, JsonConvert.SerializeObject(pack.BodyInfo));


                    var info = JObject.Parse(pack.BodyInfo);
                    if (info.Value<bool>("success"))
                    {
                        Thread.Sleep(2000);
                        var taskId = info.Value<string>("task_id");
                        var key = info?.Value<string>("task_id")?.Split('-')[1];
                        logger.LogInformation("Receive the rms with job {0} decode the key is:{1}", taskId, key);
                    };
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"CommunicationService发生错误，错误信息：{ex.Message}");
            }
        }

        #endregion
    }
}
